package com.zfl.thread.day02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo01 {
    static class BankCount {
        int balance;
        Lock lock = new ReentrantLock();

        public void withdraw(int money) {
            lock.lock();
            try {
                if (this.balance < money) {
                    System.out.println(Thread.currentThread().getName() + "余额不足[" + this.balance + "]");
                    return;
                }
                this.balance -= money;
                System.out.println(Thread.currentThread().getName() + "取款[" + money + "]，余额" + this.balance);
            } finally {
                lock.unlock();
            }
        }

        public void deposit(int money) {
            lock.lock();
            try {
                this.balance += money;
                System.out.println(Thread.currentThread().getName() + "存款[" + money + "]，余额" + this.balance);
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        BankCount bankCount = new BankCount();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                if (i % 2 == 0) {
                    bankCount.withdraw(300);
                } else {
                    bankCount.deposit(200);
                }
            }
        }, "用户1").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                if (i % 2 == 0) {
                    bankCount.withdraw(300);
                } else {
                    bankCount.deposit(200);
                }
            }
        }, "用户2").start();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                if (i % 2 == 0) {
                    bankCount.withdraw(300);
                } else {
                    bankCount.deposit(200);
                }
            }
        }, "用户3").start();
    }
}
